package com.ezjie.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ezjie.baselib.core.base.BaseFragmentActivity;
import com.ezjie.baselib.util.AppUtil;
import com.ezjie.baselib.util.LogUtils;
import com.ezjie.baselib.util.NetworkUtil;
import com.ezjie.baselib.util.OnDialogBtnClickImpl;
import com.ezjie.login.constant.Constants;
import com.ezjie.login.core.base.BaseBean;
import com.ezjie.login.core.http.HttpRequestAbstractCallBack;
import com.ezjie.login.task.RegisterTask;
import com.ezjie.login.util.UmengPages;
import com.ezjie.login.widget.AppWarnDialog;
import com.ezjie.login.widget.LinearLayoutView;
import com.ezjie.login.widget.LinearLayoutView.KeyBordStateListener;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.umeng.analytics.MobclickAgent;

/**
 * 找回密码
 * @author renyangyang
 *
 */
public class ForgetPassActivity extends BaseFragmentActivity {

	private static final int MSG_TIME_60 = 111;//60s循环倒计时
	
	private ImageView iv_login_back;
	private ImageView loginLogo;
	
	private EditText et_phone;// 手机号/邮箱
	private EditText et_auth_code;//验证码
	private Button btn_get_auth_code;//获取验证码
	private Button next_btn;//下一步
	private ImageView register_xieyi_img;//协议图片按钮
	private TextView tv_register_xieyi;//查看用户协议
	private LinearLayoutView ll_root_view;
	private LinearLayout ll_xieyi;
	

	private RegisterTask registerTask;
	private boolean isFirstSendNote = true;//判断是否是第一次发送短信  第二次就电话   只要手机号变，就算第一次
	private int currentTime = 60;//倒计时 最大为60
	private int type;//0：手机号 1：邮箱
	private String username;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_TIME_60:
				if (type == 1) {
					btn_get_auth_code.setText(currentTime
							+ "s 重新获取验证码");
				}else {
					btn_get_auth_code.setText(currentTime
							+ "s 获取语音验证码");
				}
				
				
				currentTime--;
				if (currentTime == -1) {
					mHandler.removeMessages(MSG_TIME_60);
					btn_get_auth_code.setEnabled(true);
					if (type == 1) {
						btn_get_auth_code.setText(R.string.reg_get_code);
					}else {
						btn_get_auth_code.setText(R.string.reg_get_voice_code);
					}
				}else {
					mHandler.sendEmptyMessageDelayed(MSG_TIME_60, 1000);
				}
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_app_register);
		iv_login_back = (ImageView) super.findViewById(R.id.login_back_btn);
		loginLogo = (ImageView) super.findViewById(R.id.login_logo);
		et_auth_code = (EditText) super.findViewById(R.id.et_auth_code);
		et_phone = ( EditText)super.findViewById(R.id.register_phone);
		btn_get_auth_code = (Button)super.findViewById(R.id.btn_get_auth_code);
		next_btn = (Button)super.findViewById(R.id.next_btn);
		register_xieyi_img = (ImageView) super.findViewById(R.id.register_xieyi_img);
		tv_register_xieyi = (TextView)super.findViewById(R.id.tv_register_xieyi);
		ll_root_view = (LinearLayoutView)super.findViewById(R.id.ll_app_forget);
		ll_xieyi = (LinearLayout)super.findViewById(R.id.ll_xieyi);
		ViewUtils.inject(this);
		registerTask = new RegisterTask(this);
		init();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart(UmengPages.PAGE_FORGET_PASS);
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd(UmengPages.PAGE_FORGET_PASS);
	}

	private void init() {
		username = getIntent().getStringExtra("username");
		
		iv_login_back.setOnClickListener(this);
		next_btn.setOnClickListener(this);
		btn_get_auth_code.setOnClickListener(this);
		tv_register_xieyi.setOnClickListener(this);
		register_xieyi_img.setOnClickListener(this);
		ll_xieyi.setVisibility(View.GONE);
		et_phone.setHint(R.string.login_phone_hint);
		et_phone.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);
		InputFilter[] filters = {new InputFilter.LengthFilter(100)};
		et_phone.setFilters(filters);
		et_phone.setText(username);
		
		et_auth_code.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				regEnable();
			}
		});
		et_phone.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				//改变手机号，就算第一次。
				isFirstSendNote = true;
				et_auth_code.setText("");
				btn_get_auth_code.setText(R.string.reg_get_code);
				mHandler.removeMessages(MSG_TIME_60);
				btn_get_auth_code.setEnabled(true);
				regEnable();
				
			}
		});
		ll_root_view.setKeyBordStateListener(new KeyBordStateListener() {
			
			@Override
			public void stateChange(int state) {
				switch (state) {
				case LinearLayoutView.KEYBORAD_HIDE:
					loginLogo.setVisibility(View.VISIBLE);
					break;
				case LinearLayoutView.KEYBORAD_SHOW:
					loginLogo.setVisibility(View.GONE);
					break;
				}
				
			}
		});
	}
	
	/**
	 * 判断登录按钮是否可以点击
	 * @param username
	 * @param password
	 */
	private void regEnable(){
		String phone = et_phone.getText().toString();
		String code = et_auth_code.getText().toString();
		if (TextUtils.isEmpty(phone)||TextUtils.isEmpty(code) ||code.length()<6) {
			next_btn.setEnabled(false);
		}else {
			next_btn.setEnabled(true);
		}
	}

	@Override
	public void onClickEvent(View view) {
		
		if(view.getId() == R.id.login_back_btn){
			finish();
		}else if(view.getId() == R.id.next_btn){
			doNext();
		}else if(view.getId() == R.id.btn_get_auth_code){
			getCode();
		}else if(view.getId() == R.id.tv_register_xieyi){
			
		}else if(view.getId() == R.id.register_xieyi_img){
			
		}

	}
	
	private void getCode(){
		//获得验证码
		String phone = et_phone.getText().toString();
		if (TextUtils.isEmpty(phone)) {
			AppUtil.showToast(this, R.string.reg_phone_not_null);
			return;
		}
		
		if (AppUtil.mobileFormat(phone)) {
			//手机号
			type = 0;
			btn_get_auth_code.setText(R.string.reg_sending);
			btn_get_auth_code.setEnabled(false);
			if (isFirstSendNote) {
				getYanZhengMa(type,phone,"0");
			}else {
				getYanZhengMa(type,phone,"1");
			}
		}else if (AppUtil.emailFormat(phone)) {
			//邮箱
			type = 1;
			btn_get_auth_code.setText(R.string.reg_sending);
			btn_get_auth_code.setEnabled(false);
			getYanZhengMa(type,phone,"0");
		}else {
			AppUtil.showToast(this, R.string.valid_info_hint);
		}
		
		
		
	}
	
	private void getYanZhengMa(int whatCode,String phone,String type){
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		registerTask.sendCodeByWhat(whatCode,phone, type, new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				// TODO Auto-generated method stub
				super.onStartCallBack();
			}
			@Override
			public void onSuccessCallBack(String result) {
				// TODO Auto-generated method stub
				super.onSuccessCallBack(result);
				LogUtils.d(result);
				try {
					BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
					if (baseBean != null ) {
						if (baseBean.getStatus_code() == 200) {
							if (isFirstSendNote && ForgetPassActivity.this.type == 0) {
								AppUtil.showToast(ForgetPassActivity.this, R.string.reg_code_send_success);
							}
							if (ForgetPassActivity.this.type == 1) {
								AppUtil.showToast(ForgetPassActivity.this, R.string.email_send_success);
							}
							//60s倒计时
							isFirstSendNote = false;
							currentTime = 60;
							mHandler.sendEmptyMessageDelayed(MSG_TIME_60, 1000);
						}else {
							String msg = baseBean.getMsg();
							if (TextUtils.isEmpty(msg)) {
								msg = ForgetPassActivity.this.getResources().getString(R.string.code_fail);
							}
							final AppWarnDialog appWarnDialog = new AppWarnDialog(ForgetPassActivity.this, R.style.customDialog);
							appWarnDialog.show();
							appWarnDialog.setOneButton(true);
							appWarnDialog.setMessage(msg);
							appWarnDialog.setKnowButton(R.string.confirm);
							appWarnDialog.setListener(new OnDialogBtnClickImpl() {
								public void onKnowClick() {
									appWarnDialog.cancel();
								}
							});
							
							//短信验证码发送失败
							if (ForgetPassActivity.this.type == 0) {
								isFirstSendNote = true;
							}
							btn_get_auth_code.setEnabled(true);
							if (ForgetPassActivity.this.type == 0) {
								btn_get_auth_code.setText(R.string.reg_get_code);
							}else {
								btn_get_auth_code.setText(R.string.reg_get_voice_code);
							}
						}
					}
				} catch (Exception e) {
					LogUtils.exception(e);
				}
			}
			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				// TODO Auto-generated method stub
				super.onFailureCallBack(error, msg);
				AppUtil.showToast(ForgetPassActivity.this, R.string.load_net_data_failure);
				//短信验证码发送失败
				if (ForgetPassActivity.this.type == 0) {
					isFirstSendNote = true;
				}
				btn_get_auth_code.setEnabled(true);
				if (ForgetPassActivity.this.type == 0) {
					btn_get_auth_code.setText(R.string.reg_get_code);
				}else {
					btn_get_auth_code.setText(R.string.reg_get_voice_code);
				}
				
			}
		});
	}
	
	private void doNext(){
		if (!NetworkUtil.isNetworkAvailable(this)) {
			AppUtil.showToast(this, R.string.no_network);
			return;
		}
		final String mobile = et_phone.getText().toString();
		final String verify_code = et_auth_code.getText().toString();
		if (AppUtil.mobileFormat(mobile)) {
			//手机号
			type = 0;
		}else if (AppUtil.emailFormat(mobile)) {
			//邮箱
			type = 1;
		}else {
			AppUtil.showToast(this, R.string.valid_info_hint);
			return;
		}
		
		registerTask.checkCodeByWhat(type,mobile, verify_code, new HttpRequestAbstractCallBack(this,false) {
			@Override
			public void onStartCallBack() {
				// TODO Auto-generated method stub
				super.onStartCallBack();
				AppUtil.showProgressDialog(ForgetPassActivity.this);
			}
			@Override
			public void onSuccessCallBack(String result) {
				// TODO Auto-generated method stub
				super.onSuccessCallBack(result);
				AppUtil.dismissProgressDialog();
				LogUtils.d(result);
				try {
					BaseBean baseBean = JSON.parseObject(result, BaseBean.class);
					if (baseBean != null) {
						if (baseBean.getStatus_code()==200) {
							//检查成功 跳转到重置密码   清空号码和验证码  去掉60s计时
							et_auth_code.setText("");
							et_phone.setText("");
							btn_get_auth_code.setText(R.string.reg_get_code);
							mHandler.removeMessages(MSG_TIME_60);
							btn_get_auth_code.setEnabled(true);
							
							Intent intent = new Intent(ForgetPassActivity.this, ResetPassActivity.class);
							if (type == 0) {
								intent.putExtra("mobile", mobile);
								intent.putExtra("email", "");
							}else {
								intent.putExtra("mobile", "");
								intent.putExtra("email", mobile);
							}
							
							intent.putExtra("verify_code", verify_code);
							startActivityForResult(intent, Constants.REQUEST_FORGET_PASS);
						}else {
							String msg = baseBean.getMsg();
							if (TextUtils.isEmpty(msg)) {
								msg = ForgetPassActivity.this.getResources().getString(R.string.load_net_data_failure);
							}
							final AppWarnDialog appWarnDialog = new AppWarnDialog(ForgetPassActivity.this, R.style.customDialog);
							appWarnDialog.show();
							appWarnDialog.setOneButton(true);
							appWarnDialog.setMessage(msg);
							appWarnDialog.setKnowButton(R.string.confirm);
							appWarnDialog.setListener(new OnDialogBtnClickImpl() {
								public void onKnowClick() {
									appWarnDialog.dismiss();
								}
							});
						}
					}
				} catch (Exception e) {
					LogUtils.exception(e);
				}
			}
			@Override
			public void onFailureCallBack(HttpException error, String msg) {
				// TODO Auto-generated method stub
				super.onFailureCallBack(error, msg);
				AppUtil.dismissProgressDialog();
        		AppUtil.showToast(ForgetPassActivity.this, R.string.load_net_data_failure);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_FORGET_PASS) {
			//注册成功返回的
			this.setResult(RESULT_OK);
			this.finish();
		}
	}

	
}
